package cn.com.backstage.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiT_enums;
import cn.com.api.entity.ApiU_template;
import cn.com.api.service.ApiT_enumsService;
import cn.com.api.service.ApiU_resourceService;
import cn.com.api.service.ApiU_templateService;
import cn.com.backstage.controller.base.U_templateBaseController;
import cn.com.util.*;

/**
 * H5模板管理
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(Utils.SYS_BACKSTAGE + "/")
public class U_templateController extends U_templateBaseController {

	// 日志工具
	private static Logger logger = Logger.getLogger(U_templateController.class);

	@Autowired
	private ApiU_templateService apiU_templateService;

	@Autowired
	private ApiU_resourceService apiU_resourceService;

	@Autowired
	private ApiT_enumsService apiT_enumsService;

	/**
	 * H5模板列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "template-list")
	public ModelAndView u_template_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_template_list.jsp");
		try {
			// 职业字典
			List<ApiT_enums> profession = apiT_enumsService.findT_enumssByItem_key("template_price");
			List<ApiT_enums> professions = apiT_enumsService.findT_enumssByParent_id(profession.get(0).getId() + "");
			mv.addObject("template_price", professions);

			List<ApiT_enums> module = apiT_enumsService.findT_enumssByItem_key("template_module");
			List<ApiT_enums> modules = apiT_enumsService.findT_enumssByParent_id(module.get(0).getId() + "");
			mv.addObject("template_module", modules);

			List<ApiU_template> u_templates = apiU_templateService.findU_templates();
			List<ApiU_template> u_templates_new = new ArrayList<ApiU_template>();
			List<ApiU_template> u_templates_free = new ArrayList<ApiU_template>();
			for (ApiU_template apiU_template : u_templates) {
				// 为了页面更好的处理适用模块字段显示中文,在这里处理成数组
				String type = apiU_template.getType();
				apiU_template.setType_name(type.split(","));
				// level为4时，人为业务规定为免费提供模版，存放在2个List中，便于前端处理
				String level = apiU_template.getTpl_level();
				if (level != null && !("4").equals(level)) {
					u_templates_new.add(apiU_template);
				} else {
					u_templates_free.add(apiU_template);
				}

			}
			mv.addObject("u_templates", u_templates_new);
			mv.addObject("u_templates_free", u_templates_free);
		} catch (Exception e) {
			logger.error("=============[U_templateController[u_template_list[进入H5模版列表页面失败]]]==========", e);
		}
		return mv;
	}

	/**
	 * H5模板进入新增或者编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "template-add-pre")
	public ModelAndView u_template_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_template_add.jsp");
		List<String> resultImgInfo = new ArrayList<String>();
		List<String> resultAudioInfo = new ArrayList<String>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			List<ApiT_enums> profession = apiT_enumsService.findT_enumssByItem_key("template_price");
			List<ApiT_enums> professions = apiT_enumsService.findT_enumssByParent_id(profession.get(0).getId() + "");
			mv.addObject("template_price", professions);

			List<ApiT_enums> module = apiT_enumsService.findT_enumssByItem_key("template_module");
			List<ApiT_enums> modules = apiT_enumsService.findT_enumssByParent_id(module.get(0).getId() + "");
			mv.addObject("template_module", modules);

			String id = request.getParameter("id");
			logger.info("=============[U_templateController[u_template_add_pre[参数template_id:" + id + "]]==========");
			// 分别获取图片，音乐列表，2为图片，1为音乐
			param.put("type", 2);
			List<Map<String, Object>> resultImg = apiU_resourceService.findU_resourcesByMap(param);

			for (Map<String, Object> map : resultImg) {

				resultImgInfo.add("RESOURCE_ID" + map.get("RESOURCE_ID") + "=" + map.get("RES_IMAGE"));
			}

			param.put("type", 1);
			List<Map<String, Object>> resultMusic = apiU_resourceService.findU_resourcesByMap(param);

			for (Map<String, Object> map : resultMusic) {

				resultAudioInfo.add("RESOURCE_ID" + map.get("RESOURCE_ID") + "=" + map.get("RES_IMAGE"));
			}
			mv.addObject("template_img_list", resultImg);
			mv.addObject("template_audio_list", resultMusic);
			mv.addObject("resultImgInfo", resultImgInfo);
			mv.addObject("resultAudioInfo", resultAudioInfo);
			mv.addObject("template_img_list", resultImg);

			if (request.getParameter("id") != null) {
				ApiU_template u_template = apiU_templateService.findU_templateByTemplateId(Integer.valueOf(id));
				mv.addObject("u_template", u_template);
			}
		} catch (Exception e) {
			logger.error("=============[U_templateController[u_template_add_pre[进入H5模版编辑页面失败]]]==========", e);
		}
		return mv;
	}

	/**
	 * H5模板进入预览页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "template-display-pre")
	public ModelAndView u_template_display_pre(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_template_display.jsp");
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			List<ApiT_enums> profession = apiT_enumsService.findT_enumssByItem_key("template_price");
			List<ApiT_enums> professions = apiT_enumsService.findT_enumssByParent_id(profession.get(0).getId() + "");
			mv.addObject("template_price", professions);

			List<ApiT_enums> module = apiT_enumsService.findT_enumssByItem_key("template_module");
			List<ApiT_enums> modules = apiT_enumsService.findT_enumssByParent_id(module.get(0).getId() + "");
			mv.addObject("template_module", modules);
			String id = request.getParameter("id");
			logger.info(
					"=============[U_templateController[u_template_display_pre[参数template_id:" + id + "]]==========");
			// 分别获取图片，音乐列表，2为图片，1为音乐
			param.put("type", 2);
			List<Map<String, Object>> resultImg = apiU_resourceService.findU_resourcesByMap(param);
			param.put("type", 1);
			List<Map<String, Object>> resultMusic = apiU_resourceService.findU_resourcesByMap(param);
			mv.addObject("template_img_list", resultImg);
			mv.addObject("template_audio_list", resultMusic);

			if (request.getParameter("id") != null) {
				ApiU_template u_template = apiU_templateService.findU_templateByTemplateId(Integer.valueOf(id));
				mv.addObject("u_template", u_template);
			}
		} catch (Exception e) {
			logger.error("=============[U_templateController[u_template_display_pre[进入H5模版预览页面失败]]]==========", e);
		}
		return mv;
	}

	/**
	 * H5模板新增操作
	 */
	@RequestMapping(value = "template-add")
	public void u_template_add(HttpServletRequest request, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String template_id = request.getParameter("template_id");
			String tpl_name = request.getParameter("tpl_name");
			String tpl_thumb = request.getParameter("tpl_thumb");
			String bg_image = request.getParameter("bg_image");
			String bg_audio = request.getParameter("bg_audio");
			String[] type = request.getParameterValues("typetags");
			String tpl_desc = request.getParameter("tpl_desc");
			String tpl_level = request.getParameter("tpl_level");
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String now_time = sd.format(new Date());
			String type_split = "";
			// 对前端的适用模块做拼接处理，插入数据库
			if (type != null) {
				for (String string : type) {
					type_split += string + ",";
				}
				if (type_split.length() > 0) {
					type_split = type_split.substring(0, type_split.length() - 1);
				}
			}
			logger.info("=============[U_templateController[u_template_add[参数tpl_name:" + tpl_name + ",tpl_thumb:"
					+ tpl_thumb + ",bg_image:" + bg_image + ",template_id:" + template_id + "]]]==========");
			logger.info("=============[U_templateController[u_template_add[参数bg_audio:" + tpl_name + ",tpl_desc:"
					+ tpl_desc + ",tpl_level:" + tpl_level + ",type:" + type_split + "]]]==========");

			// add
			if (template_id == null || (template_id.trim()).equals("")) {
				ApiU_template u_template = new ApiU_template();
				u_template.setTpl_name(tpl_name);
				if (tpl_thumb != null && !("").equals(tpl_thumb)) {
					u_template.setTpl_thumb(tpl_thumb);
				}
				u_template.setBg_image(bg_image);
				u_template.setBg_audio(bg_audio);
				u_template.setType(type_split);
				u_template.setTpl_desc(tpl_desc);
				u_template.setTpl_level(tpl_level);
				u_template.setCreate_time(now_time);
				u_template.setStatus("1");
				apiU_templateService.insertU_template_info(u_template);
			}
			// edit
			else {
				ApiU_template u_template = apiU_templateService
						.findU_templateByTemplateId(Integer.valueOf(template_id));
				u_template.setTemplate_id(Integer.parseInt(template_id));
				u_template.setTpl_name(tpl_name);
				if (tpl_thumb != null && !("").equals(tpl_thumb)) {
					u_template.setTpl_thumb(tpl_thumb);
				}
				u_template.setBg_image(bg_image);
				u_template.setBg_audio(bg_audio);
				u_template.setType(type_split);
				u_template.setTpl_desc(tpl_desc);
				u_template.setTpl_level(tpl_level);
				u_template.setModify_time(now_time);
				u_template.setStatus("1");
				apiU_templateService.updateU_template_info(u_template);
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		} catch (Exception e) {
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "添加失败！");
			logger.error("=============[U_templateController[u_template_add[H5模板增加失败]]]==========", e);
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 模版上下架状态更新
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "template-grounding")
	public void u_template_grounding(HttpServletRequest request, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String template_id = request.getParameter("id");
			String status = request.getParameter("status");

			logger.info("=============[U_templateController[u_template_grounding[参数status:" + status + ",template_id:"
					+ template_id + "]]]==========");

			ApiU_template u_template = apiU_templateService.findU_templateByTemplateId(Integer.valueOf(template_id));
			u_template.setTemplate_id(Integer.parseInt(template_id));
			// 根据状态值更改上下架状态
			if (status != null && "1".equals(status)) {
				u_template.setStatus("0");
			}
			if (status != null && "0".equals(status)) {
				u_template.setStatus("1");
			}
			apiU_templateService.updateU_template_info(u_template);

			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "上下架成功！");
		} catch (Exception e) {
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "上下架失败！");
			logger.error("=============[U_templateController[u_template_grounding[H5模板上下架模版更新失败]]]==========", e);
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "template-delete")
	public void u_template_delete(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		try {
			int ret_i = apiU_templateService.deleteU_template_info(Integer.valueOf(id));
			if (ret_i > 0) {
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "删除成功！");
			}
			JsonUtil.printJson(response, JsonUtil.object2json(map));
		} catch (Exception e) {
			logger.error("=============[U_templateController[u_template_delete[H5模板删除失败]]]==========", e);
		}
		// delete
	}

}
